package com.quanyan.handler;

import com.quanyan.api.CmdInterface;
import com.quanyan.factory.CommandFactory;
import org.apache.log4j.Logger;
import org.jboss.netty.channel.*;

import com.quanyan.entity.Command;
import com.quanyan.entity.ParamStruct;
import com.quanyan.util.UuidUtil;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateEvent;

/**
 * 
 * @ClassName: ServerHandler
 * @Description: 服务处理类
 * @author chuntu tuchun168@163.com
 * @date 2016年5月3日 上午11:18:42
 *
 */
public class ServerHandler extends SimpleChannelUpstreamHandler {

	private static final Logger logger = Logger.getLogger(ServerHandler.class);

	@Override
	public void handleUpstream(final ChannelHandlerContext ctx, ChannelEvent e)
			throws Exception {
		if (e instanceof IdleStateEvent) {
			if(((IdleStateEvent)e).getState() == IdleState.ALL_IDLE){
				logger.info("用户通道过时！！！");
				//关闭通道
				Command command = new Command();
				command.setHead("*Q");
				command.setCmd("");
				command.setData("用户通道过时, 通道关闭!!!");
				ChannelFuture write = ctx.getChannel().write(command);
				write.addListener(new ChannelFutureListener() {

					@Override
					public void operationComplete(ChannelFuture future) throws Exception {
						ctx.getChannel().close();
					}
				});
			}
		} else {
			super.handleUpstream(ctx, e);
		}
	}

	/**
	 * 通道建立
	 */
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		logger.info("Channel connected");
		ParamStruct paramStruct = new ParamStruct();
		paramStruct.setSessionId(UuidUtil.generateUuid());
		paramStruct.setChannel(e.getChannel());

		// 将参数做为ChannelHandlerContext的附件
		ctx.setAttachment(paramStruct);
		// 将channel保存到全局变量中
		// ChannelContext context = new ChannelContext(e.getChannel(),
		// System.currentTimeMillis());

	}

	/**
	 * 通道被关闭
	 */
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx,
			ChannelStateEvent e) throws Exception {
		logger.info("Channel disconnected");
		if (ctx.getAttachment() != null) {
			try {
				removeChannel((ParamStruct) ctx.getAttachment());
			} catch (Exception e1) {
				logger.error(e1.getMessage()+"通道被关闭异常",e1);
			}
		}
	}

	/**
	 * 通道收到数据
	 */
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {

		try {
			Command basicCommand = (Command) e.getMessage();
			logger.info("server received message " + e.getMessage());
			ParamStruct paramStruct = (ParamStruct) ctx.getAttachment();
			paramStruct.setCommand(basicCommand);
			CmdInterface command= CommandFactory.create(paramStruct);
			command.doHandle();
		} catch (Exception e1) {
			logger.error("远程调用异常" + e1.getMessage(), e1);
		}
	}

	/**
	 * Channel发生异常，关闭Channel
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		e.getCause().printStackTrace();
		logger.error("Channel Exception, " + e.getCause().getMessage());
		try {
			e.getChannel().close();
		} catch (Exception e2) {
			logger.error(e2.getMessage()+"Channel发生异常，关闭Channel异常",e2);
		}
	}

	/**
	 * 移除通道
	 * 
	 * @param paramStruct
	 * @throws Exception
	 */
	private void removeChannel(ParamStruct paramStruct) throws Exception {
		// 已经通过登录验证
		/*
		 * Long userId = paramStruct.getUserId(); if (userId != null && userId
		 * != 0) { SocketChannelMng socketChannelMng =
		 * SocketChannelMng.getInstance();
		 * 
		 * if (socketChannelMng.getSocketChannelMap().containsKey(userId)) {
		 * socketChannelMng.getSocketChannelMap().remove(userId); logger.info(
		 * "User Channel is removed from SocketChannelMng.SocketChannelMap, key is "
		 * + userId); }
		 * GlobalLogic.updateOnlineState(paramStruct.getCompanyId(),
		 * paramStruct.getUserId(), UserState.USER_STATE_OFF_LIINE); }
		 */

	}
}
